package se.webbzon.boltzmann.game.npc;

import se.webbzon.boltzmann.game.character.CharacterActionEnum;
import se.webbzon.boltzmann.game.character.CharacterFacing;
import se.webbzon.boltzmann.game.object.player.AbstractPlayerCharacter;
import se.webbzon.boltzmann.npc.AbstractNPC;
import se.webbzon.boltzmann.npc.NPCDuty;

public class StandingDuty extends NPCDuty {
	
	// The priority of this duty
	private static final int priority = 0;
	
	// The default ignore range
	private static final double defaultIgnoreRange = 64;
	
	// The maximal range between the non-player character and
	// the player where the non-player character still ignores the
	// player
	private final double ignoreRange;
	
	/*============================================================
	Constructors
	============================================================*/
	
	/** Creates a new standing duty in the given world. **/
	public StandingDuty(AbstractNPC npc) {
		this(npc,defaultIgnoreRange);
	}
	
	/** Creates a new standing duty in the given world. **/
	public StandingDuty(AbstractNPC npc, double ignoreRange) {
		super(priority,npc);
		this.ignoreRange = ignoreRange;
	}
	
	/*============================================================
	Public Methods
	============================================================*/

	@Override public void onBegin() {
		getNPC().setAction(CharacterActionEnum.STAND);
	}
	
	@Override public void onStep() {
		AbstractNPC npc = getNPC();
		if (npc instanceof GameNPC) {
			GameNPC gameNPC = (GameNPC) npc;
			if (!gameNPC.getPlayers().isEmpty()) {
				// Check if there are any players nearby
				AbstractPlayerCharacter player = gameNPC.closestPlayer();
				if (npc.distanceTo(player) < ignoreRange) {
					// Face the player
					final double facing = Math.atan2(	npc.getZ()-player.getZ(), 
														player.getX()-npc.getX());
					if (facing < 0)
						npc.setFacing(facing + 2*Math.PI);
					else 
						npc.setFacing(facing);	
				} else {
					if (npc.getFacing() == CharacterFacing.LEFT_UP)
						npc.setFacing(CharacterFacing.LEFT_DOWN);
					else if (npc.getFacing() == CharacterFacing.RIGHT_UP)
						npc.setFacing(CharacterFacing.RIGHT_DOWN);
				}
			}
		}
	}
	
	@Override public void onEnd() {};

}
